//
//  QSOtherSelectCompanyViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/5/5.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSOtherSelectCompanyViewController.h"
#import "QSHeaderSearchView.h"
#import "QSProblemReprotInterface.h"
#import "QSCompanyCell.h"
#import "BRPickerView.h"
#import "QSVisitInterFace.h"
#import "QSSingInInterface.h"
@interface QSOtherSelectCompanyViewController ()<QSHeaderSearchViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic, strong)QSHeaderSearchView *headerSearchView;
/** 选择街道label*/
@property (nonatomic, strong)UILabel *selectStreetLabel;
/** 右侧图片*/
@property (nonatomic, strong)UIImageView *rightImageView;

@property (nonatomic, strong)NSArray *townArr;//街道数组

@property (nonatomic, strong)NSString *townShipId;//街道id
@property (nonatomic, strong)NSString *name;//公司名称
@property (nonatomic, strong) UILabel *headerLabel;//头部提示文案
@property (nonatomic, strong) UILabel *footerLabel;//尾部提示文案
@property (nonatomic, assign)BOOL isBundle;//判断当前是否是绑定企业
@property (nonatomic, assign)NSInteger searchPageIndex;//搜索结果的pageindex
@property (nonatomic, assign)NSInteger bindingPageIndex;//绑定的Pageindex

@property (nonatomic, strong) NSString *epAllCompany;//是否展示所有企业
@end

static NSString * const companyCell = @"CompanyCell";

@implementation QSOtherSelectCompanyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupForDismissKeyboard];//键盘回收
    [self configSubView];
    self.isBundle = YES;//默认显示绑定企业列表
    _searchPageIndex = 1;
    _bindingPageIndex = 1;
    [self getCompanyListWithPageIndex:_bindingPageIndex];//获取绑定企业列表
    [self addNewRefreshHeader];//添加带判定显示数据的头部
    [self addNewRefreshFooter];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
}
- (void)configSubView{
    self.tableView.frame = CGRectMake(0, kNavgationBarHeight + kRealValue(29), kScreenWidth, kScreenHeight - kNavgationBarHeight - kRealValue(10 + 29));
    self.view.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"QSCompanyCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:companyCell];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    [self.view addSubview:self.headerSearchView];
    [self.view addSubview:self.headerLabel];
    [self.headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(10));
        make.top.equalTo(self.headerSearchView.mas_bottom).offset(kRealValue(10));
    }];
    self.footerLabel = [UILabel labelWithName:@"- 非绑定企业可通过搜索查找企业 -" font:[UIFont QSFontOfSize14] textColor:[UIColor QSColorGray999999] textAlignment:NSTextAlignmentCenter];
    _footerLabel.frame = CGRectMake(0, 0, kScreenWidth, kRealValue(30));
    self.tableView.tableFooterView = _footerLabel;
    
}
//重写添加头部/尾部
- (void)addNewRefreshHeader {
    WeakSelf(weakSelf);
    [self.tableView addRefreshHeaderWithRefreshingBlock:^{
        if (weakSelf.isBundle) {
            weakSelf.bindingPageIndex = 1;
            [weakSelf getCompanyListWithPageIndex:weakSelf.bindingPageIndex];
        }else{
            weakSelf.searchPageIndex = 1;
            [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.searchPageIndex];
        }
    }];
}

- (void)addNewRefreshFooter {
    WeakSelf(weakSelf);
    [self.tableView addRefreshFooterWithRefreshingBlock:^{
        if (weakSelf.isBundle) {
            weakSelf.bindingPageIndex ++;
            [weakSelf getCompanyListWithPageIndex:weakSelf.bindingPageIndex];
        }else{
            weakSelf.searchPageIndex ++;
            [weakSelf tableViewShouldUpdateDataByPageIndex:weakSelf.searchPageIndex];
        }
    }];
}

- (QSHeaderSearchView *)headerSearchView{
    if (!_headerSearchView) {
        _headerSearchView = [[QSHeaderSearchView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavgationBarHeight)];
        _headerSearchView.delegate = self;
    }
    return _headerSearchView;
}

#pragma mark - Lazy Load
- (UILabel *)headerLabel{
    if (!_headerLabel) {
        _headerLabel = [UILabel labelWithName:@"我绑定的企业" font:[UIFont QSFontOfSize14] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentCenter];
    }
    return _headerLabel;
}

- (NSMutableArray *)searchEnterprisesArr{
    if (!_searchEnterprisesArr) {
        _searchEnterprisesArr = [NSMutableArray array];
    }
    return _searchEnterprisesArr;
}

- (NSMutableArray *)bindingEnterprisesArr{
    if (!_bindingEnterprisesArr) {
        _bindingEnterprisesArr = [NSMutableArray array];
    }
    return _bindingEnterprisesArr;
}

- (UIImageView *)rightImageView{
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_select_open"]];
    }
    return _rightImageView;
}

#pragma mark - HeaderSearchViewDelegate
//开始搜索企业
- (void)headerSearchViewDidSearchAction:(QSHeaderSearchView *)searchView{
    if (searchView.searchTextField.text.length > 0) {
        self.name = searchView.searchTextField.text;
        self.isBundle = NO;//不显示绑定列表
        self.bindingPageIndex = 1;
        NSLog(@"name = %@", self.name);
        [self updateWithIsBundle:self.isBundle];
    }
}

//清空操作
- (void)headerSearchViewDidClickClear:(QSHeaderSearchView *)searchView{
    searchView.searchTextField.text = @"";
    self.name = @"";
    self.townShipId = @"";
    //        self.selectStreetLabel.text = @"  所属镇街";
    self.isBundle = YES;
    self.bindingPageIndex = 1;
    self.searchPageIndex = 1;
    [searchView.rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [self updateWithIsBundle:self.isBundle];
//        [self tableViewShouldUpdateDataByPageIndex:1];
}
//根据判断展示数据
- (void)updateWithIsBundle:(BOOL)isBundle{
    if (isBundle) {
        //显示绑定企业
        [self.searchEnterprisesArr removeAllObjects];
        self.headerLabel.text = @"我绑定的企业";
        if (self.bindingEnterprisesArr.count == 0) {
            self.footerLabel.hidden = YES;
        }else{
            self.footerLabel.hidden = NO;
            self.headerLabel.hidden = NO;
        }
        [self getCompanyListWithPageIndex:1];
    }else{
        //展示非绑定企业
        self.tableView.mj_footer.hidden = NO;
        self.tableView.mj_header.hidden = NO;
        self.headerLabel.hidden = YES;
//        self.headerLabel.text = @"未绑定的企业";
        self.footerLabel.hidden = YES;
        [self tableViewShouldUpdateDataByPageIndex:1];
    }
}
//返回上一页
- (void)headerSearchViewDidClickBack:(QSHeaderSearchView *)searchView{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault; //UIStatusBarStyleLightContent  白
}
#pragma mark - TableViewDelegate && DataSource
- (void)tableViewShouldUpdateDataByPageIndex:(NSInteger)pageIndex{
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中..."];
    [QSVisitInterFace getApiSearchCompanyWithPageIndex:pageIndex EpAllCompany:self.epAllCompany  CompanyName:_name andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSBindingEnterprisesModel * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode){
            if (pageIndex == 1) {
                [self.searchEnterprisesArr removeAllObjects];
            }
            [self.searchEnterprisesArr addObjectsFromArray:result.list];
            NSLog(@"%@,", self.searchEnterprisesArr);
            [self.tableView reloadData];
            [self.tableView qs_endRefreshing];
            if (pageIndex >= result.pages) {
                //                self.tableView.mj_footer.hidden = YES;
                [self endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
        }
    }];
}

#pragma mark - Api - 获取绑定企业列表
- (void)getCompanyListWithPageIndex:(NSInteger)pageIndex{
     [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
    [QSSingInInterface getShowAllCompanyAndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSString * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (result) {
            self.epAllCompany = result;
        }
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            [self getCompanyWithEpAllCompany:result pageIndex:pageIndex];
        }
    }];
}

- (void)getCompanyWithEpAllCompany:(NSString *)epAllCompany pageIndex:(NSInteger)pageIndex{
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中"];
    [QSSingInInterface getCompanyListWithPageIndex:pageIndex EpAllCompany:epAllCompany andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSBindingEnterprisesModel * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (pageIndex == 1) {
                [self.bindingEnterprisesArr removeAllObjects];
            }
            [self.bindingEnterprisesArr addObjectsFromArray:result.list];
            NSLog(@"%@,", self.bindingEnterprisesArr);
            if (self.bindingEnterprisesArr.count == 0) {
                self.footerLabel.hidden = YES;
                self.headerLabel.hidden = YES;
            }
            [self.tableView reloadData];
            [self.tableView qs_endRefreshing];
            if (pageIndex >= result.pages) {
                //                self.tableView.mj_footer.hidden = YES;
                [self endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
        }
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isBundle) {
        return self.bindingEnterprisesArr.count;
    }else{
        return self.searchEnterprisesArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QSCompanyCell *cell = [tableView dequeueReusableCellWithIdentifier:companyCell];
    if (self.isBundle) {
        cell.bindingEnterprisesModel = self.bindingEnterprisesArr[indexPath.row];
    }else{
        cell.bindingEnterprisesModel = self.searchEnterprisesArr[indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kRealValue(80 + 10);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isBundle) {
        QSVisitInfoCompanyListModel *model = self.bindingEnterprisesArr[indexPath.row];
        if (self.didSelectCompanyBlock) {
            self.didSelectCompanyBlock(model);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        QSVisitInfoCompanyListModel *model = self.searchEnterprisesArr[indexPath.row];
        if (self.didSelectCompanyBlock) {
            self.didSelectCompanyBlock(model);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
    [self.tableView endEditing:YES];
    [self.selectStreetLabel endEditing:YES];
    QSCompanyCell *cell = [self.tableView dequeueReusableCellWithIdentifier:companyCell];
    [cell.contentView endEditing:YES];
}

#pragma mark - DZNEmptyDataSetSource
/**
 *  返回标题文字
 */
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text;
    if (self.isBundle) {
        text = @"您暂未绑定企业，可通过输入企业名称进行模糊搜索";
    }else{
        text = @"未搜索到相关企业";
    }
    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f],
                                     NSForegroundColorAttributeName: [UIColor QSColorBlack666666] };
    return [[NSAttributedString alloc]initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    scrollView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    return [UIImage imageNamed:@"ic_company_null"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
